<?php
namespace app\api\controller\wanlshop;

use addons\shopro\library\chat\traits\GetLinkerTrait;
use addons\wanlshop\library\WanlPay\WanlPay;
use addons\wanlshop\library\WanlSdk\Common;
use app\admin\controller\wanlshop\Spot;
use app\admin\controller\wanlshop\Yiyatong;
use app\admin\model\Area;
use app\admin\model\wanlshop\AddressSpot;
use app\admin\model\wanlshop\QrcodeLog;
use app\admin\model\wanlshop\Verification;
use app\api\model\wanlshop\Category;
use app\api\model\wanlshop\Goods;
use app\api\model\wanlshop\OrderGoods;
use app\api\model\wanlshop\Third;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\common\model\TestContent;
use think\Cache;
use think\Db;
use think\Exception;
use phpqrcode\QRcode;
use DateTime;
/**
 * WanlShop订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['chengQrCode','confirmReceipt','separateAccounts','cancelRefund','instructions'];
	protected $noNeedRight = ['*'];
    
	/**
     * 获取订单列表
     *
     * @ApiSummary  (WanlShop 订单接口获取订单列表)
     * @ApiMethod   (GET)
	 * 2020年5月12日23:25:40
	 *
	 * @param string $state 状态
	 */
    public function getOrderList()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
    	$state = $this->request->request('state');
        if ($state && $state != 0) {
        	$where['state'] = $state;
        }
        $where['status'] = 'normal';
        $where['user_id'] = $this->auth->id;
		// 列表	
		$list = model('app\api\model\wanlshop\Order')
			->where($where)
			->field('id,shop_id,state,spot_id,paymenttime,is_integral')
			->order('updatetime desc')
			->paginate()
			->each(function($order, $key){
				$goods = model('app\api\model\wanlshop\OrderGoods')
					->where(['order_id'=> $order->id])
					->field('id,title,goods_id,image,difference,price,market_price,number,refund_status,deduct_points,actual_payment')
					->select();
				$order['goods'] = $goods;
				// 获取支付 1.1.2升级
				$order['pay'] = model('app\api\model\wanlshop\Pay')
					->where(['order_id' => $order->id, 'type' => 'goods'])
					->field('number, price, order_price, freight_price, discount_price, actual_payment,score')
					->find();
				$order['shop'] = $order->shop?$order->shop->visible(['shopname']):[];
				return $order;
			});
        foreach ($list as &$item){
//
            $spot = AddressSpot::where('id',$item['spot_id'])->find();
            if($spot){
                //自提店
                if($spot['type'] == 1){
                    $paymentTime = $item['paymenttime']; // 付款时间（时间戳）
                    $comeTime = $spot['cometime']; // 小时数
                    // 将付款时间转换为 DateTime 对象
                    $paymentDateTime = new DateTime();
                    $paymentDateTime->setTimestamp($paymentTime);
                    // 添加指定的小时数
                    $paymentDateTime->modify("+{$comeTime} hours");
                    // 获取当前时间
                    $currentDateTime = new DateTime();
                    // 比较时间
                    if ($paymentDateTime > $currentDateTime) {
                        $item['cometime'] = $paymentDateTime->format('Y-m-d H:i:s');;
                    } else {
                        $item['cometime'] = "";
                    }
                    $item['spot_text'] = '待自提';
                }
                //核销门店
                if($spot['type'] == 2){
                    $item['spot_text'] = '待核销';
                    $item['cometime'] = '';
                }
            }else{
                $item['spot_text'] = '';
                $item['cometime'] = '';
            }
        }
		$list?($this->success('ok',$list)):($this->error(__('网络繁忙')));
    }
    
    /**
	 * 获取购买过的商品
	 *
	 * @ApiSummary  (WanlShop 订单接口获取订单列表)
	 * @ApiMethod   (GET)
	 * 2020年5月12日23:25:40
	 *
	 * @param string $state 状态
	 */
	public function getBuyList()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    $order_ids = [];
	    foreach (model('app\api\model\wanlshop\Order')->where([ 'user_id' => ['eq', $this->auth->id], 'state' => ['in', '2,3,4,6'], 'status' => ['eq', 'normal']])->select() as $order) {
			  $order_ids[] = $order['id'];  
		}
	    $goods = model('app\api\model\wanlshop\OrderGoods')
			->where('order_id', 'in', $order_ids)
			->select();
		// 列表	
		$list = model('app\api\model\wanlshop\Goods')
			->where('id', 'in', array_keys(array_flip(array_column($goods, 'goods_id'))))
			->field('id, image, title, price')
			->order('updatetime desc')
			->paginate();
		$this->success('ok', $list);
	}
    
    
	/**
	 * 查询用户店铺订单记录 
	 *
	 * @ApiSummary  (查询用户店铺订单记录 1.0.2升级)
	 * @ApiMethod   (POST)
	 *
	 * @param string $shop_id 店铺ID
	 */
	public function getOrderListToShop()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if($this->request->isPost()){
			$shop_id = $this->request->post('shop_id');
			$shop_id ? '':($this->error(__('Invalid parameters')));
			$list = model('app\api\model\wanlshop\Order')
				->where(['shop_id' => $shop_id, 'user_id' => $this->auth->id, 'status' => 'normal'])
				->field('id,shop_id,order_no,state')
				->order('updatetime desc')
				->select();
			// 订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
			foreach ($list as $row) {
			    $row['goods'] = model('app\api\model\wanlshop\OrderGoods')
			    	->where(['order_id'=> $row->id])
			    	->field('id,title,image,difference,price,market_price,number,refund_status')
			    	->select();
			}
			$this->success(__('发送成功'), $list);
		}
		$this->error(__('非法请求'));
	}
	
    /**
     * 获取订单详情
     *
     * @ApiSummary  (WanlShop 订单接口获取订单详情)
     * @ApiMethod   (GET)
	 * 
	 * @param string $id 订单ID
	 */
    public function getOrderInfo()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$id = $this->request->request('id');
		$id ? $id : ($this->error(__('非法请求')));
		$order = model('app\api\model\wanlshop\Order')
			->where(['id' => $id, 'user_id' => $this->auth->id])
			->field('id,shop_id,order_no,isaddress,express_no,express_name,freight_type,state,createtime,paymenttime,delivertime,taketime,dealtime,spot_id,is_refund,is_integral')
			->find();
		$order ? $order : ($this->error(__('网络异常')));
		// 输出配置
		$config = get_addon_config('wanlshop');
		$order['config'] = $config['order'];
		switch ($order['state']) {
			case 1:
				$express = [
					'context' => '付款后，即可将宝贝发出',
					'status' => '尚未付款',
					'time' => date('Y-m-d H:i:s', $order['createtime'])
				];
				break;
			case 2:
				$express = [
					'context' => '商家正在处理订单',
					'status' => '已付款',
					'time' => date('Y-m-d H:i:s', $order['paymenttime'])
				];
				break;
			default: // 获取物流
				$eData = model('app\api\model\wanlshop\KuaidiSub')
					->where(['express_no' => $order['express_no']])
					->find();
				// 兼容PHP7.4	1.1.5升级
				if(!empty($eData['data'])){
				    $ybData = json_decode($eData['data'], true);
					$express = $ybData[0];
				}else{
					$express = [
						'status' => '已发货',
						'context' => '包裹正在等待快递小哥揽收~',
						'time' => date('Y-m-d H:i:s', $order['delivertime'])
					];
				}
		}
		// 获取物流
		$order['logistics'] = $express;
		// 获取地址
		$order['address'] = model('app\api\model\wanlshop\OrderAddress')
			->where(['order_id' => $id, 'user_id' => $this->auth->id])
			->order('isaddress desc')
			->field('id,name,mobile,address,address_name')
			->find();
		// 获取店铺
		$order['shop'] = $order->shop?$order->shop->visible(['shopname']):[];
        //获取自提点或门店信息
        $order['spot'] = model('app\admin\model\wanlshop\AddressSpot')
            ->where(['id'=> $order['spot_id']])
            ->find();
		// 获取订单商品
		$order['goods'] = model('app\api\model\wanlshop\OrderGoods')
			->where(['order_id'=> $id])
			->field('id,goods_id,title,image,difference,price,market_price,actual_payment,discount_price,freight_price,number,refund_id,refund_status,deduct_points')
			->select();
		// 获取支付 1.1.2升级
		$order['pay'] = model('app\api\model\wanlshop\Pay')
			->where(['order_id' => $order->id, 'type' => 'goods'])
			->field('id, pay_no, number, price, order_price, freight_price, discount_price, actual_payment,score')
			->find();
        $spot = AddressSpot::where('id',$order['spot_id'])->find();
        if($spot){
            //自提店
            if($spot['type'] == 1){
                $paymentTime = $order['paymenttime']; // 付款时间（时间戳）
                $comeTime = $spot['cometime']; // 小时数
                // 将付款时间转换为 DateTime 对象
                $paymentDateTime = new DateTime();
                $paymentDateTime->setTimestamp($paymentTime);
                // 添加指定的小时数
                $paymentDateTime->modify("+{$comeTime} hours");
                // 获取当前时间
                $currentDateTime = new DateTime();
                // 比较时间
                if ($paymentDateTime > $currentDateTime) {
                    $order['cometime'] = $paymentDateTime->format('Y-m-d H:i:s');;
                } else {
                    $order['cometime'] = "";
                }
                $order['spot_text'] = '待自提';
            }
            //核销门店
            if($spot['type'] == 2){
                $order['spot_text'] = '待核销';
                $order['cometime'] = '';
            }
        }else{
            $order['spot_text'] = '';
            $order['cometime'] = '';
        }
        //获取核销码
        $order['qrcode'] = \app\api\model\wanlshop\Qrcode::where('order_id',$id)->select();
        //核销码过期时间
        $spot_end_time = Goods::where('id',$order['goods'][0]['goods_id'])->find();
        $order['out_time'] = $spot_end_time['spot_end_time'];
		$this->success('ok',$order);
    }
	
	/**
	 * 确认收货
	 *
	 * @ApiSummary  (WanlShop 订单接口确认收货)
	 * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
	public function confirmOrder()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    if ($this->request->isPost()) {
		    $id = $this->request->post('id');
			$id ? $id : ($this->error(__('非法请求')));
			// 判断权限
			$order = model('app\api\model\wanlshop\Order')
				->where(['id' => $id, 'state'=> 3, 'user_id' => $this->auth->id])
				->find();
			if(!$order){
				$this->error(__('订单异常'));
			}
			Db::startTrans();
			try {
			    // 获取支付 1.1.2升级
			    $pay = model('app\api\model\wanlshop\Pay')->get(['order_id' => $id, 'type' => 'goods']);
			    // 平台转款给商家
			    controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$pay['price'], $order['shop']['user_id'], '买家确认收货', 'pay', $order['order_no']);
			    // 查询是否有退款
			    $refund = model('app\api\model\wanlshop\Refund')
			    	->where(['order_id' => $id, 'state' => 4, 'order_type' => 'goods'])
			    	->select();
			    // 退款存在
			    if($refund){
			    	foreach($refund as $value){
			    		controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-$value['price'], $order['shop']['user_id'], '该订单存在的退款', 'pay', $order['order_no']);
			    	}
			    }
			    // 更新退款
			    $order->save(['state' => 4,'taketime' => time()],['id' => $id]);
			    Db::commit();
			} catch (Exception $e) {
			    Db::rollback();
				$this->error($e->getMessage());
			}
		    $this->success('ok', $order ? true : false);
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 取消订单
	 *
	 * @ApiSummary  (WanlShop 订单接口取消订单)
	 * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
	public function cancelOrder()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    if ($this->request->isPost()) {
		    $id = $this->request->post('id');
			$id ? $id : ($this->error(__('非法请求')));
			// 判断权限
			$this->getOrderState($id) != 1 ? ($this->error(__('订单异常'))):'';
			$row = model('app\api\model\wanlshop\Order')->get(['id' => $id, 'user_id' => $this->auth->id]);
			$result = $row->allowField(true)->save(['state' => 7]);
			// 还原优惠券 1.0.2升级
			if($row['coupon_id'] != 0){
				model('app\api\model\wanlshop\CouponReceive')->where(['id' => $row['coupon_id'], 'user_id' => $this->auth->id])->update(['state' => 1]);
			}
			// 释放库存 1.0.3升级
			foreach(model('app\api\model\wanlshop\OrderGoods')->all(['order_id' => $row['id']]) as $vo){
				// 查询商品是否需要释放库存
				if(model('app\api\model\wanlshop\Goods')->get($vo['goods_id'])['stock'] == 'porder'){
					model('app\api\model\wanlshop\GoodsSku')->where('id', $vo['goods_sku_id'])->setInc('stock', $vo['number']);
				}
			}
            //如果使用了积分要归还
            $pay = \app\admin\model\wanlshop\Pay::where('order_id',$id)->find();
            $user = \app\admin\model\User::where('id',$this->auth->id)->find();
            model('app\common\model\ScoreLog')->save([
                'user_id'=>$this->auth->id,
                'score'=>$pay['score'],
                'before'=>$user['score'],
                'after'=>$user['score'] + $pay['score'],
                'memo'=>'取消订单,积分归还'
            ]);

            $user->score = $user['score']+$pay['score'];
            $user->save();

		    $this->success('ok', $result ? true : false);
		}
		$this->error(__('非法请求'));
	}
	
    /**
     * 删除订单
     *
     * @ApiSummary  (WanlShop 订单接口删除订单)
     * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
    public function delOrder()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
		    $id = $this->request->post('id');
			$id ? $id : ($this->error(__('非法请求')));
			// 判断权限
			$state = $this->getOrderState($id);
			$state == 6 || $state == 7 ? '' :($this->error(__('非法请求')));
			$order = model('app\api\model\wanlshop\Order')
				->save(['status' => 'hidden'],['id' => $id]);
			$this->success('ok', $order ? true : false);
		}
		$this->error(__('非法请求'));
    }
	
    
	/**
	 * 修改地址
	 *
	 * @ApiSummary  (WanlShop 订单接口修改地址)
	 * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
	public function editOrderAddress()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    if ($this->request->isPost()) {
		    $order_id = $this->request->post('id');
			$address_id = $this->request->post('address_id');
			$order_id || $address_id ? $order_id : ($this->error(__('非法请求')));
			// 判断权限
			$this->getOrderState($order_id) > 3 ? ($this->error(__('订单异常'))):'';
			// 订单
			$order = model('app\api\model\wanlshop\Order')
				->where(['id' => $order_id, 'user_id' => $this->auth->id])
				->find();
			
			//判断是否修改过
			if($order['isaddress'] == 1){
				$this->error(__('已经修改过一次了'));
			}else{
				// 获取地址
				$address = model('app\api\model\wanlshop\Address')
					->where(['id' => $address_id, 'user_id' => $this->auth->id])
					->find();
				// 修改地址
				$data = model('app\api\model\wanlshop\OrderAddress')->save([
						'user_id' => $this->auth->id,
						'shop_id' => $order->shop_id,
						'order_id'  => $order_id,
						'isaddress' => 1,
						'name' => $address['name'],
						'mobile' => $address['mobile'],
						'address' => $address['province'].'/'.$address['city'].'/'.$address['district'].'/'.$address['address'],
						'address_name' => $address['address_name'],
						'location' => $address['location']
					]);
				// 修改状态
				model('app\api\model\wanlshop\Order')->where(['id' => $order_id, 'user_id' => $this->auth->id])->update(['isaddress' => 1]);
				$this->success('ok',$data);
			}
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 评论订单
	 *
	 * @ApiSummary  (WanlShop 订单接口评论订单)
	 * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
	public function commentOrder()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    if ($this->request->isPost()) {
		    $post = $this->request->post();
			$post ? $post : ($this->error(__('数据异常')));
			$user_id = $this->auth->id;
			// 判断权限
			$this->getOrderState($post['order_id']) != 4 ? ($this->error(__('已经评论过或订单异常'))):'';
			// 生成列表
			$commentData = [];
			foreach ($post['goodsList'] as $value) {
				$commentData[] = [
					'user_id' => $user_id,
					'shop_id' => $post['shop']['id'],
					'order_id' => $post['order_id'],
					'goods_id' => $value['goods_id'],
					'order_goods_id' => $value['id'],
					'order_type' => 'goods',
					'state' => $value['state'],
					'content' => $value['comment'],
					'suk' => $value['difference'],
					'images' => $value['imgList'],
					'score' => round((($post['shop']['describe'] + $post['shop']['service'] + $post['shop']['deliver'] + $post['shop']['logistics']) / 4) ,1),
					'score_describe' => $post['shop']['describe'],
					'score_service' => $post['shop']['service'],
					'score_deliver' => $post['shop']['deliver'],
					'score_logistics' => $post['shop']['logistics'],
					'switch' => 0
				];
				//评论暂不考虑并发，为列表提供好评付款率，减少并发只能写进商品中
				model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('comment');
				if($value['state'] == 0){
					model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('praise');
				}else if($value['state'] == 1){
					model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('moderate');
				}else if($value['state'] == 2){
					model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('negative');
				}
			}
			if(model('app\api\model\wanlshop\GoodsComment')->saveAll($commentData)){
				$order = model('app\api\model\wanlshop\Order')
					->where(['id' => $post['order_id'], 'user_id' => $user_id])
					->update(['state' => 6]);
			}
			//更新店铺评分
			$score = model('app\api\model\wanlshop\GoodsComment')
				->where(['user_id' => $user_id])
				->select();
			// 从数据集中取出
			$describe = array_column($score,'score_describe');
			$service = array_column($score,'score_service');
			$deliver = array_column($score,'score_deliver');
			$logistics = array_column($score,'score_logistics');
			// 更新店铺评分
			model('app\api\model\wanlshop\Shop')
				->where(['id' => $post['shop']['id']])
				->update([
					'score_describe' => bcdiv(array_sum($describe), count($describe), 1),
					'score_service' => bcdiv(array_sum($service), count($service), 1),
					'score_deliver' => bcdiv(array_sum($deliver), count($deliver), 1),
					'score_logistics' => bcdiv(array_sum($logistics), count($logistics), 1)
				]);
		    $this->success('ok',[]);
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 获取订单物流状态
	 *
	 * @ApiSummary  (WanlShop 订单接口获取订单物流状态)
	 * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
	public function getLogistics()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    if ($this->request->isPost()) {
		    $id = $this->request->post('id');
			$id ? $id : ($this->error(__('非法请求')));
			//获取订单
			$order = model('app\api\model\wanlshop\Order')
				->where(['id' => $id, 'user_id' => $this->auth->id])
				->field('id,shop_id,express_name,express_no,order_no,createtime,paymenttime,delivertime')
				->find();
			// 获取快递
			switch ($order['state']) {
				case 1:
					$express[] = [
						'context' => '付款后，即可将宝贝发出',
						'status' => '尚未付款',
						'time' => date('Y-m-d H:i:s', $order['createtime'])
					];
					break;
				case 2:
					$express[] = [
						'context' => '商家接受到您的订单，准备出库',
						'status' => '已下单',
						'time' => date('Y-m-d H:i:s', $order['paymenttime'])
					];
					break;
				default: // 获取物流
					$express = model('app\api\model\wanlshop\KuaidiSub')
						->where(['express_no' => $order['express_no']])
						->find();
					if($express){
						$express = json_decode($express['data'], true);
					}else{
						$express[] = [
							'context' => '打包完成，正在等待快递小哥揽收~',
							'status' => '仓库处理中',
							'time' => date('Y-m-d H:i:s', $order['delivertime'])
						];
					}
			}
			$order['kuaidi'] = $order->kuaidi ? $order->kuaidi->visible(['name','logo','tel']) : [];
			$order['express'] = $express;
		    $this->success('ok',$order);
		}
		$this->error(__('非法请求'));
	}
	
    /**
     * 确认订单
     *
     * @ApiSummary  (WanlShop 订单接口确认订单)
     * @ApiMethod   (POST)
	 * 
	 * @param string $data 商品数据
	 */
    public function getOrderGoodsList()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
		    $request = $this->request->post();
		    // 订单数据
		    $order = array();
            $spuInfoList = array();
		    $map = array();
			// 1.0.5升级 修复客户端地址更新
			$where = !empty($request['address_id']) ? ['id' => $request['address_id'], 'user_id' => $this->auth->id] : ['user_id' => $this->auth->id, 'default' => 1];
            $address=[];
		    // 合计
		    $statis = array(
				"allnum" => 0,
				"allsub" => 0
			);
            $points_type = 0;
            $points_money = 0;
            $max_points = 0;
            $shop_id = 0;
		    foreach ($request['data'] as $post) {
				$redis = Common::redis();
		    	// 商品详情
		    	$goods = model('app\api\model\wanlshop\Goods')
		    		->where('id', $post['goods_id'])
		    	    ->field('id, shop_id, shop_category_id,delivery_method, activity_type, title,image,stock,freight_id,sales,points_type,points_deduction,take_proportion,price')
		    	    ->find();
                $shop_id = $goods['shop_id'];
                $goods['id'] = (string)$goods['id'];
                //是否能积分兑换(只要有一个能就都能)
                if ($goods['points_type'] > 0) {
                    $points_type = 1;

                }
		    	// 获取SKU
				$sku = model('app\api\model\wanlshop\GoodsSku')
		    		->where('id', $post['sku_id'])
		    	    ->field('id,goods_id,difference,price,market_price,stock,weigh')
		    	    ->find();
					
				// 1.1.2升级 判断是否超出库存
				$sku_key = 'goods_'.$sku['goods_id'].'_'.$sku['id'];
				if($post['number'] > $redis->llen("{$sku_key}")){
					$this->error("商家正在补货中，请稍后抢购！");
				}
                if($goods['delivery_method'] == 1){
                    // 地址
                    $address = model('app\api\model\wanlshop\Address')
                        ->where($where)
                        ->field('id,name,mobile,province,city,district,address')
                        ->find();
                    // 1.1.6升级
                    if(!$address){
                        $this->error(__('请添加收货地址'));
                    }
                    $goods['freight'] = $this->freight($goods['freight_id'], $sku['weigh'], $post['number'], $address['city']);
                }else{
                    $goods['freight'] = [
                      'id'  =>  0,
                      'price'  =>  0,
                      'name'  =>  '包邮',
                    ];
                }
				// 获取快递及价格
				// 获取SKU
		    	$goods['sku'] = $sku;
		    	// 数量
		    	$goods['number'] = $post['number'];

                if($goods['points_type'] == 1){
                    $points_money = $points_money+ bcmul($goods['number'], $sku['price'], 2);
                }
                if($goods['points_type'] == 2){
                    $chatConfig = get_addon_config('wanlshop');
                    //一积分抵扣金额
                    $deduction_amount = $chatConfig['config']['deduction_amount'];
                    //商品>商家>分类  获取当前积分抵扣比例
                    $points_deduction = 0;
                    $take_proportion = 0;
                    if($goods['points_deduction'] > 0 ){
                        $points_deduction = $goods['points_deduction'];
                        $take_proportion = $goods['take_proportion'];

                    }else{
                        $shop = \app\api\model\wanlshop\Shop::where('id',$goods['shop_id'])->find();
                        if($shop['points_deduction'] > 0 ){
                            $points_deduction = $shop['points_deduction'];
                            $take_proportion = $shop['take_proportion'];
                        }else{
                            $cate =  Category::where('id',$shop['category_id'])->find();
                            $points_deduction = $cate['points_deduction'];
                            $take_proportion = $cate['take_proportion'];
                        }
                    }
                    //算出最多抵扣金额
                    $price = $sku['price']*($take_proportion/100);
                    $price = $price*($points_deduction/100);
                    $price = $price*$post['number'];
                    $price = floor($price * 100) / 100;
                    $max = ceil($price / $deduction_amount);
                    if ($max < 1 && $price > 0) {
                        $max = 1;
                    }
                    $points_money = $points_money+$price;
                    $max_points = $max_points+$max;
                }
			    // 格式化
		        if (empty($map[$goods['shop_id']])) {

		            $order[] = array(
					    "shop_id"   => $goods['shop_id'],
					    "shop_name" => $goods->shop ? $goods->shop->visible(['shopname'])['shopname']:[],
					    "products"  => [$goods],
						"coupon" => [],
						"freight"  => [$goods['freight']],
					    "number"    => $goods['number'],
						"sub_price" => bcmul($sku['price'], $goods['number'], 2)
					);
		            $map[$goods['shop_id']] = $goods;
		        } else {

					// 追加1-*
		            foreach ($order as $key => $value) {
		                if ($value['shop_id'] == $goods['shop_id']) {
		            		array_push($order[$key]['products'],$goods);
							array_push($order[$key]['freight'],$goods['freight']);
		            		$order[$key]['number'] += $post['number'];
							$order[$key]['sub_price'] = bcadd($order[$key]['sub_price'], bcmul($sku['price'], $post['number'], 2), 2);
		                    break;
		                }
		            }
		        }
				// 所有店铺统计
				$statis['allnum'] += $goods['number'];

                //怡亚通获取运费数据
                $spuInfoList[] = [
                    'quantity'=>$post['number'], //商品数量
                    'spuId'=>$post['goods_id'], //商品spuId
                ];

		    }
            //是否是怡亚通商品
            $shop = \app\api\model\wanlshop\Shop::where('id',$shop_id)->find();
            if($shop['shop_type'] == 1){ //1是怡亚通专卖店
                //请求第三方获取运费
                $yiyatong = new Yiyatong();

                $area = Area::where('name',$address['city'])->find();
                $yfData = [
                    'spuInfoList'=>$spuInfoList,
                    'cityId'=>$area['id']
                ];
                $yytYf = $yiyatong->calculate($yfData);
                foreach ($order as $key => $value) {
                        // 更新订单的运费信息
                        $order[$key]['freight'] = [
                            'id' => $value['freight'][0]['id'], // 保持之前的运费 ID
                            'name' => '怡亚通运费',  // 名称可以根据需求调整
                            'price' => $yytYf // 使用新计算的运费
                        ];

                        // 备份运费价格,用于还原
                        $order[$key]['freight_price_bak'] = $yytYf;

                        // 更新订单价格
                        $order[$key]['order_price'] = $order[$key]['sub_price']; // 原价
                        $order[$key]['sub_price'] = bcadd($order[$key]['sub_price'], $yytYf, 2); // 加上运费后的价格
                        $statis['allsub'] = bcadd($statis['allsub'], $order[$key]['sub_price'], 2); // 更新总价
                }
            }else{
			    // 获取运费策略-店铺循环
			    foreach ($order as $key => $value) {
                    $config = model('app\api\model\wanlshop\ShopConfig')
                        ->where('shop_id',$value['shop_id'])
                        ->find();
                    if($config){
                        if($config['freight'] == 0){
                            // 运费叠加
                            $order[$key]['freight'] = [
                                'id' => $value['freight'][0]['id'],
                                'name' => '运费叠加',
                                'price' => array_sum(array_column($value['freight'],'price'))
                            ];
                        }else if($config['freight'] == 1){
                            // 以最低结算
                            array_multisort(array_column($value['freight'],'price'),SORT_ASC,$value['freight']);
                            $order[$key]['freight'] = [
                                'id' => $value['freight'][0]['id'],
                                'name' => $value['freight'][0]['name'],
                                'price' => $value['freight'][0]['price']
                            ];
                        }else if($config['freight'] == 2){
                            // 以最高结算
                            array_multisort(array_column($value['freight'],'price'),SORT_DESC,$value['freight']);
                            $order[$key]['freight'] = [
                                'id' => $value['freight'][0]['id'],
                                'name' => $value['freight'][0]['name'],
                                'price' => $value['freight'][0]['price']
                            ];
                        }
                        $order[$key]['order_price'] = $order[$key]['sub_price'];
                        // 2020年9月19日12:10:59 添加快递价格备份,用于还原运费
                        $order[$key]['freight_price_bak'] = $order[$key]['freight']['price'];
                        // 1.0.8升级
                        $order[$key]['sub_price'] = bcadd($order[$key]['sub_price'], $order[$key]['freight']['price'], 2);
                        $statis['allsub'] = bcadd($statis['allsub'], $order[$key]['sub_price'], 2);
                    }else{
                        $this->error(__('商家未配置运费组策略，暂不支持下单'));
                    }
                }
			}
			// 传递Token
			$datalist['token'] = Common::creatToken('orderToken_'. $this->auth->id);
		    // 地址
		    $datalist['addressData'] = $address;
			// 订单
		    $datalist['orderData']['lists'] = $order;
		    $datalist['orderData']['statis'] = $statis;
            //查看是否可以积分抵扣
            $datalist['points_type'] = $points_type;
            //最多可抵扣金额
            $datalist['points_money'] = $points_money;
            $datalist['max_points'] = $max_points;
		    $this->success('ok', $datalist);
		} else {
		    $this->error(__('非法请求'));
		}
    }
    
    /**
     * 提交订单
     *
     * @ApiSummary  (WanlShop 订单接口提交订单)
     * @ApiMethod   (POST)
     * 
     * @param string $data 数组
     */
    public function addOrder()
    {
    	//设置过滤方法
    	$this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
			$result = false;
    		$params = $this->request->post();
            $params['is_point'] = $this->request->post('is_point',0);
			// 验证Token
//			if(array_key_exists('token', $params)){
//				if(!Common::checkToken($params['token'], 'orderToken_'. $this->auth->id)){
//					$this->error(__('页面安全令牌已过期！请重返此页'));
//				}
//			}else{
//				$this->error(__('非法提交，未传入Token'));
//			}
    		$user_id = $this->auth->id; // 用户ID
			$addressList = [];
			$goodsList = [];
			$payList = [];
            //判断是什么类型的订单
            $good = Goods::where('id',$params['order']['lists'][0]['products'][0]['goods_id'])->find();
            $address_id = '';
            $address = [];
            $spot_id = '';
                if(array_key_exists('spot_id',$params['order'])){
                    $spot_id = $params['order']['spot_id']; // 地址ID
                    $spot = AddressSpot::where('id',$spot_id)->find();
                }

                // 判断是否有地址 1.0.2升级
                if(array_key_exists('address_id',$params['order'])){
                    $address_id = $params['order']['address_id']; // 地址ID
                }

                if($address_id){
                    // 查询地址
                    $address = model('app\api\model\wanlshop\Address')
                        ->where(['id' => $address_id,'user_id' =>$user_id])
                        ->find();
                    // 1.0.4升级
                    if(!isset($address)){
                        $this->error(__('地址异常，没有找到该地址'));
                    }
                }


    		// 判断订单是否合法 1.0.4升级
    		if(array_key_exists('lists',$params['order'])){
    			$lists = $params['order']['lists'];
    			if(!isset($lists) && count($lists) == 0){
    				$this->error(__('订单繁忙ERR001：请返回商品详情重新提交订单'));
    			}
    		}else{
    			$this->error(__('订单繁忙ERR002：请返回商品详情重新提交订单'));
    		}
            $score = $this->request->post('score',0);
            $points_money = $this->request->post('points_money',0);
			// 数据库事务操作
    		Db::startTrans();
    		try {
                $freight =  [];
                $spuInfoList = array();
				// 遍历已店铺分类列表
				foreach ($lists as $item) {
					// 获取店铺ID
					$shop_id = $item['shop_id'];
					// 查询店铺配置
					$config = model('app\api\model\wanlshop\ShopConfig')
						->where('shop_id', $shop_id)
						->find();
					// 如果不存在，按照累计运费
					if(!$config){
						$config['freight'] = 0;
					}
					// 生成订单
					$order = new \app\api\model\wanlshop\Order;
					$order->freight_type = $config['freight'];
					$order->user_id = $user_id;
                    $order->spot_id = $spot_id;
					$order->shop_id = $shop_id;
					$order->order_no = $shop_id.$user_id;
                    if($params['is_point'] == 1){
                        $order->is_integral = 1;
                    }
					if(isset($item['remarks'])){
					    $order->remarks = $item['remarks'];
					}
					// 2021年3月04日 06:54:11 修改优惠券逻辑
					$coupon = model('app\api\model\wanlshop\CouponReceive')
						->where(['id' => $item['coupon_id'], 'user_id' => $user_id, 'shop_id' => $shop_id])
						->find();
					$order->coupon_id = $coupon ? $coupon['id'] : 0;
					// 要补充活动ID
					if($order->save()){
						$priceAll = 0; // 总价格
						$numberAll = 0; // 总数量
						$freightALL = [];
						$shopGoodsAll = [];
                        $delivery_method = '';//配送方式
                        $store_id = [];//自提点
                        $shop_id = [];//店铺
                        $good_type = '';
						// 计算订单价格
						foreach ($item['products'] as $k=>&$data){

							$redis = Common::redis();
							// 查询商品 1.2.0升级
							$goods = model('app\api\model\wanlshop\Goods')
								->where(['id' => $data['goods_id'], 'status' => 'normal'])
								->find();
                            $store = array_merge(explode(",", $goods['platform_address_spot_id']), explode(",", $goods['self_address_spot_id']));
                            $store_id = array_merge($store,$store_id);
                            $store_num = count($store_id);
                            $store_nums = count(array_unique($store_id));
                            if($goods['good_type']==1){
                                $good_num = count($item['products']);

                                if($good_num > 1){
                                    $this->error('多个虚拟商品不可以同时下单');
                                }
                            }
                            if($k>0){
                                if($shop_id != $goods['shop_id']){
                                    $this->error('请勿跨店铺下单');
                                }

                                if($delivery_method != $goods['delivery_method']){
                                    $this->error('商品配送方式不相同');
                                }else {
                                    if($goods['delivery_method'] == 2){
                                        if($store_num == $store_nums ){
                                            $this->error('没有相同的自提点');
                                        }
                                    }
                                    if($goods['delivery_method'] == 3){
                                        if($good_type != $goods['good_type']){
                                            $this->error('虚拟商品不可与实物商品一起下单');
                                        }
                                        if($goods['good_type'] == 0){
                                            if($store_num == $store_nums ){
                                                $this->error('没有相同的自提点');
                                            }
                                        }
                                    }
                                }
                            }
                            $delivery_method = $goods['delivery_method'];
                            $shop_id = $goods['shop_id'];
                            $good_type = $goods['good_type'];

							// 获取sku
							$sku = model('app\api\model\wanlshop\GoodsSku')->get($data['sku_id']);
							// 1.1.2升级
							$sku_key = 'goods_'.$sku['goods_id'].'_'.$sku['id'];
							// 1.1.0升级
							if(!$goods) throw new Exception("对不起当前商品不存在或已下架");
							// 效验shop_id是否正确 1.1.2升级
							if($goods['shop_id'] != $shop_id) throw new Exception("网络异常SHOPID错误！");
							// 1.1.2升级 提交订单判断库存
							if($sku['stock'] <= 0){
								throw new Exception("商品被抢光了");
							}else if($sku['stock'] < $data['number']){
								throw new Exception("库存不足");
							}
							// 库存计算方式:porder=下单减库存,payment=付款减库存
							if($goods['stock'] == 'porder'){
								// 1.1.2升级
								if($data['number'] > $redis->llen("{$sku_key}")){
									throw new Exception("系统繁忙，请稍后抢购！");
								}else{
									for ($i = 0; $i < $data['number']; $i ++) {
										$redis->rpop("{$sku_key}");
									}
									$sku->setDec('stock', $data['number']); // 1.0.3升级
								}
							}
                            // 生成运费
							if($address){
                                $freight = $this->freight($goods['freight_id'], $sku['weigh'], $data['number'], $address['city']);
                            }else{
                                $freight = [
                                    'id'  =>  0,
                                    'price'  =>  0,
                                    'name'  =>  '包邮',
                                ];
                            }


                            //获取商品的比例
                            if($goods['take_proportion']!=0&&$goods['sharing_proportion']!=0){
                                $take_proportion = $goods['take_proportion'];
                                $sharing_proportion = $goods['sharing_proportion'];
                            }else{
                                $shop =\app\api\model\wanlshop\Shop::where('id',$goods['shop_id'])->find();
                                if($shop['take_proportion']!=0&&$shop['sharing_proportion']!=0){
                                    $take_proportion = $shop['take_proportion'];
                                    $sharing_proportion = $shop['sharing_proportion'];
                                }else{
                                    $category =\app\api\model\wanlshop\Category::where('id',$shop['category_id'])->find();
                                    $take_proportion = $category['take_proportion'];
                                    $sharing_proportion = $category['sharing_proportion'];
                                }
                            }

                            if ($params['is_point'] == 1){
                                // 商品列表 actual_payment
                                $shopGoodsAll[] = [
                                    'order_id' => $order->id, // 获取自增ID
                                    'goods_id' => $goods['id'],
                                    'shop_id' => $shop_id,
                                    'title' => $goods['title'],
                                    'image' => $goods['image'],
                                    'goods_sku_sn' => $sku['sn'],
                                    'goods_sku_id' => $sku['id'],
                                    'difference' => join(',', $sku['difference']),
                                    'market_price' => $sku['market_price'], // 市场价
                                    'price' => $params['priceAll'], // 原价
                                    'freight_price' => $freight['price']??0, //快递价格
                                    'discount_price' => 0, // 优惠金额
                                    'actual_payment' =>$params['priceAll'], // 1.0.6修复 实际支付，因为要和总价进行计算
                                    'number' => $data['number'],
                                    'deduct_points'=>$params['deduct_points'],
                                    'sharing_proportion'=>$sharing_proportion,  //分佣比例
                                    'take_proportion'=>$take_proportion, //抽成比例
                                ];
                                $user = \app\admin\model\User::where('id',$this->auth->id)->find();
                                $score = $user->score;
                                $user->score -= $params['deduct_points'];
                                $after = $user->score;
                                $user->save();

                            }else{
                                // 商品列表 actual_payment
                                $shopGoodsAll[] = [
                                    'order_id' => $order->id, // 获取自增ID
                                    'goods_id' => $goods['id'],
                                    'shop_id' => $shop_id,
                                    'title' => $goods['title'],
                                    'image' => $goods['image'],
                                    'goods_sku_sn' => $sku['sn'],
                                    'goods_sku_id' => $sku['id'],
                                    'difference' => join(',', $sku['difference']),
                                    'market_price' => $sku['market_price'], // 市场价
                                    'price' => $sku['price'], // 原价
                                    'freight_price' => $freight['price']??0, //快递价格
                                    'discount_price' => 0, // 优惠金额
                                    'actual_payment' => bcmul($sku['price'], $data['number'], 2), // 1.0.6修复 实际支付，因为要和总价进行计算
                                    'number' => $data['number'],
                                    'sharing_proportion'=>$sharing_proportion,  //分佣比例
                                    'take_proportion'=>$take_proportion, //抽成比例
                                ];
                            }

							$freightALL[] = $freight;
							$priceAll = bcadd($priceAll, bcmul($sku['price'], $data['number'], 2), 2); // 计算价格
							$numberAll += $data['number']; // 计算数量

                            //怡亚通获取运费数据
                            $spuInfoList[] = [
                                'quantity'=>$data['number'], //商品数量
                                'spuId'=>$data['goods_id'], //商品spuId
                            ];
						}
						if($address){
                            //查看是否是怡亚通订单走三方运费
                            $shop = \app\api\model\wanlshop\Shop::where('id',$shop_id)->find();
                            if($shop['shop_type'] == 1){
                                $yiyatong = new Yiyatong();

                                $area = Area::where('name',$address['city'])->find();
                                $yfData = [
                                    'spuInfoList'=>$spuInfoList,
                                    'cityId'=>$area['id']
                                ];
                                $yytYf = $yiyatong->calculate($yfData);
                                $freight['price'] = $yytYf;
                                $freight['name'] = '怡亚通运费';
                            }else{

                                // 计算运费叠加方案
                                if($config['freight'] == 0){
                                    // 运费叠加
                                    $freight = [
                                        'id' => $freightALL[0]['id'],
                                        'name' => '合并运费',
                                        'price' => array_sum(array_column($freightALL,'price'))
                                    ];
                                }else if($config['freight'] == 1){ // 以最低结算
                                    array_multisort(array_column($freightALL,'price'),SORT_ASC,$freightALL);
                                    $freight = [
                                        'id' => $freightALL[0]['id'],
                                        'name' => $freightALL[0]['name'],
                                        'price' => $freightALL[0]['price']
                                    ];
                                }else if($config['freight'] == 2){ // 以最高结算
                                    array_multisort(array_column($freightALL,'price'),SORT_DESC,$freightALL);
                                    $freight = [
                                        'id' => $freightALL[0]['id'],
                                        'name' => $freightALL[0]['name'],
                                        'price' => $freightALL[0]['price']
                                    ];
                                }
                            }

                            $freight_price = $freight['price'];  //快递金额
                        }else{
                            $freight_price = 0;
                        }


						$price = bcadd($priceAll, $freight_price, 2); // 总价格
						$coupon_price = 0; //优惠券金额
						$discount_price = 0; // 优惠金额，因为后续版本涉及到活动减免，所以优惠金额要单独拎出来
                        //如果使用积分抵扣
                        $score_amount = 0;
                        if($score>0){
                            //计算抵扣金额
                            //获取 wanlshop 配置文件
                            $config = get_addon_config('wanlshop');
                            $deduction_amount = $config['config']['deduction_amount'];
                            $score_amount = $score*$deduction_amount;
                            //总金额 =（订单金额 - 积分金额）
                            //最多抵扣金额
                            $maxMoney = $points_money;
                            if ($score_amount > $maxMoney) {
                                // 如果抵扣金额大于最大抵扣金额，使用最大抵扣金额
                                $price = bcsub($priceAll, $maxMoney, 2);
                                $score_amount = $maxMoney;
                            } else {
                                // 否则使用计算出的抵扣金额
                                $price = bcsub($priceAll, $score_amount, 2);
                            }
                            // 如果价格小于0，返回0
                            if ($price < 0) {
                                $price = '0.00'; // 保留两位小数
                            }
                            $user = \app\admin\model\User::where('id',$this->auth->id)->find();
                            // 保存用户积分的变更记录
                            model('app\common\model\ScoreLog')->save([
                                'user_id'=>$this->auth->id,
                                'score'=>$score * -1,
                                'before'=>$user['score'],
                                'after'=>$user['score'] - $score,
                                'memo'=>'购买积分商品'
                            ]);
                            $user->save([
                                'score'=>$user['score'] - $score
                            ]);
                        }
						// 如果优惠券存在
						if($coupon) {
							// 判断是否可用
							if($priceAll >= $coupon['limit']){
								// 优惠金额
								if($coupon['type'] == 'reduction' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'reduction')){
									$coupon_price = $coupon['price']; 
									//总金额 =（订单金额 - 优惠券金额）+ 运费
									$price = bcadd(bcsub($priceAll, $coupon_price, 2), $freight['price'], 2);
								}
								// 折扣金额
								if($coupon['type'] == 'discount' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'discount')){
									// 排除异常折扣，还原百分之
									$discount = $coupon['discount'] > 10 ? bcdiv($coupon['discount'], 100, 2) : bcdiv($coupon['discount'], 10, 2);
									// 优惠金额 = 订单金额 - 订单金额 * 折扣
									$coupon_price = bcsub($priceAll, bcmul($priceAll, $discount, 2), 2);
									$price = bcadd(bcsub($priceAll, $coupon_price, 2), $freight['price'], 2);
								}
								// 免邮金额
								if($coupon['type'] == 'shipping'){
									$coupon_price = $freight_price;
									$price = $priceAll;
									$freight_price = 0;
								}
								$discount_price = $coupon_price;
								
								// 总优惠金额 1.1.3弃用
								// $paycoupon = 0;
								// 总实际支付金额 1.1.3弃用
								// $payment = 0;   
								foreach ($shopGoodsAll as $row) {
									$goods_price = bcmul($row['price'], $row['number'], 2);
									$goods_discount_price = round($coupon_price * ( $goods_price / $priceAll ), 2); // 优惠金额
									// 1.0.8升级,修复包邮
									$actual_payment = $coupon['type'] === 'shipping' ? $goods_price : bcsub($goods_price, $goods_discount_price, 2);
									//优惠价格
									$row['discount_price'] = $goods_discount_price; 
									// 实际支付 1.0.9升级
									$row['actual_payment'] = $actual_payment <= 0 ? '0.01' : $actual_payment; 
									$row['freight_price'] = $freight_price;
									// 1.0.8升级 1.1.3弃用
									// $paycoupon = bcadd($paycoupon, $goods_discount_price, 2); 
									// $payment = bcadd($payment, $actual_payment, 2);
									$goodsList[] = $row;
								}
								
								// 更新已使用数量
								model('app\api\model\wanlshop\Coupon')
									->where(['id' => $coupon['coupon_id']])
									->setInc('usenum');
								// 修改该优惠券状态 已用
								$coupon->allowField(true)->save(['state' => 2]);
							}else{
								model('app\api\model\wanlshop\Order')->destroy($order->id);
								throw new Exception('订单金额'.$priceAll.'元，不满'.$coupon['limit'].'元');
							}
						}else{
							foreach ($shopGoodsAll as $row) {
								$goodsList[] = $row;
							}
						}
                        if($params['is_point'] == 1){
                            $price = $params['price'];
                            $priceAll = $params['priceAll'];
                            $score = $params['deduct_points'];
                        }
						// 生成支付
						$payList[] = [
							'user_id' => $user_id,
							'shop_id' => $shop_id,
							'order_id'  => $order->id,
							'order_no'  => $order->order_no,
							'pay_no' => $order->order_no,
							'type' => 'goods', // 1.0.8升级
                            'price'  => $price ,
//							'price'  => $price <= 0 ? 0.01 : $price,  // 支付价格，系统要求至少支付一分钱
							'order_price' => $priceAll, // 订单总金额
							'coupon_price' => $coupon_price,  // 优惠券金额
							'freight_price' => $freight_price, // 快递费
							'discount_price' => $discount_price, // 优惠金额
							'number'  => $numberAll,
                            'score_price'=>$score_amount,
                            'score'=>$score
						];
						if($address){
                            // 生成地址
                            $addressList[] = [
                                'user_id' => $user_id,
                                'shop_id' => $shop_id,
                                'order_id'  => $order->id,
                                'name' => $address['name'],
                                'mobile' => $address['mobile'],
                                'address' => $address['province'].'/'.$address['city'].'/'.$address['district'].'/'.$address['address'],
                                'address_name' => $address['address_name'],
                                'location' => $address['location']
                            ];
                        }else{
                            $addressList[] = [
                                'user_id' => $user_id,
                                'shop_id' => $shop_id,
                                'order_id'  => $order->id,
                                'name' => $spot['name'],
                                'mobile' => $spot['phone'],
                                'address' => $spot['address'],
                                'address_name' => $spot['address'],
                                'location' => ''
                            ];
                        }

					}else{
						throw new Exception('网络繁忙，创建订单失败！');
					}
				}
    		    model('app\api\model\wanlshop\OrderAddress')->saveAll($addressList);
    		    model('app\api\model\wanlshop\OrderGoods')->saveAll($goodsList);
    		    $result = model('app\api\model\wanlshop\Pay')->saveAll($payList);
                //是否是怡亚通商品进行第三方订单创建

    		    Db::commit();
    		} catch (Exception $e) {
    		    Db::rollback();
    			$this->error($e->getMessage());
    		}
    		if ($result !== false) {



				$this->success('返回成功', ['list' => $result,'token' => Common::creatToken('orderToken_'. $this->auth->id)]);
    		} else {
    		    $this->error(__('订单异常，请返回重新下单'));
    		}
    	} else {
    	    $this->error(__('非法请求'));
    	}
    }
    
	/**
	 * 订单状态码（方法内使用）
	 *
	 * @ApiSummary  (WanlShop 返回订单状态码)
	 * @ApiMethod   (POST)
	 * 
	 * @param string $id 订单ID
	 */
	private function getOrderState($id = 0)
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
	    $order = model('app\api\model\wanlshop\Order')
	    	->where(['id' => $id, 'user_id' => $this->auth->id])
	    	->find();
		return $order['state'];
	}
	
	/**
	 * 获取运费模板和子类 内部方法 
	 * 1.1.6升级
	 * @param string $id  运费ID
	 * @param string $weigh  商品重量
	 * @param string $number  商品数量
	 * @param string $city  邮递城市
	 */
	private function freight($id = null, $weigh = null, $number = 0, $city = '南山区')
	{
		// 运费模板
		$data = model('app\api\model\wanlshop\ShopFreight')->where('id', $id)->field('id,delivery,isdelivery,name,valuation')->find();
        if(!$data){
            $data['price'] = 0;
            $data['name'] = '包邮';
            $data['id'] = 0;
            return $data;
		}
		$data['price'] = 0;
		// 是否包邮:0=自定义运费,1=卖家包邮
		if($data['isdelivery'] == 0){
			// 获取地址编码 1.1.0升级
			$list = model('app\api\model\wanlshop\ShopFreightData')
				->where([
					['EXP', Db::raw('FIND_IN_SET('.model('app\common\model\Area')->get(['name' => $city])->id.', citys)')],
					'freight_id' => $id
				])
				->find();
			// 查询是否存在运费模板数据
			if(!$list){
				$list = model('app\api\model\wanlshop\ShopFreightData')->get(['freight_id' => $id]);
			}
			
			// 计价方式:0=按件数,1=按重量,2=按体积  1.0.2升级 
			if($data['valuation'] == 0){
				if($number <= $list['first']){
					$price = $list['first_fee'];
				}else{
					$additional = $list['additional'] > 0 ? $list['additional'] : 1; //因为要更换vue后台，临时方案，为防止客户填写0
					$price = bcadd(bcmul(ceil(($number - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
				}
			}else{
				$weigh = $weigh * $number; // 订单总重量
				if($weigh <= $list['first']){ // 如果重量小于等首重，则首重价格
					$price = $list['first_fee'];
				}else{
					$additional = $list['additional'] > 0 ? $list['additional'] : 1;
					$price = bcadd(bcmul(ceil(($weigh - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
				}
			}
			$data['price'] = $price;
		}
		return $data;
	}
    //选择自提点
    public function goods_spot()
    {

    }
    public function scorePrice()
    {
        $request = $this->request->post();
        $config = get_addon_config('wanlshop');
        $deduction_amount = $config['config']['deduction_amount'];
        //计算抵扣金额
        $amount =   bcmul($request['score'], $deduction_amount, 2);
        //最多抵扣金额
        $maxMoney = $request['points_money'];
        if ($amount > $maxMoney) {
            // 如果抵扣金额大于最大抵扣金额，使用最大抵扣金额
            $price = bcsub($request['price'], $maxMoney, 2);
        } else {
            // 否则使用计算出的抵扣金额
            $price = bcsub($request['price'], $amount, 2);
        }

        // 如果价格小于0，返回0
        if ($price < 0) {
            $price = '0.00'; // 保留两位小数
        }
        $this->success('ok', $price);
    }
    //生成核销码
    public function chengQrCode()
    {
        $request = $this->request->post();

        $order_id = 102;
        $publicPath = realpath(ROOT_PATH . 'public') . DIRECTORY_SEPARATOR;
        $order = \app\api\model\wanlshop\Order::where('id', $order_id)->find();
        if (!empty($order['spot_id']) && $order['spot_id'] != 0) {
            $spot = AddressSpot::where('id', $order['spot_id'])->find();
            // 自提店
            $salt = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 16);
            $fileBaseName = 'qr' . time(); // 基础文件名

            if ($spot['type'] == 1) {
                $file = $fileBaseName . '.png';
                QRcode::png($salt, $publicPath . 'uploads/qrcode/' . $file);
                \app\admin\model\wanlshop\Qrcode::create([
                    'image' => 'uploads/qrcode/' . $file,
                    'status' => 0,
                    'order_id' => $order_id, // 修正为整数值
                    'salt' => $salt
                ]);
            }
            // 核销店
            if ($spot['type'] == 2) {

                $orderGoods = OrderGoods::where('order_id', $order_id)->select();

                // 1个码因为一个订单有很多核销商品
//                if (count($orderGoods) > 0) {
//                    $file = $fileBaseName . '.png';
//                    QRcode::png($salt, $publicPath . 'uploads/qrcode/' . $file);
//                    \app\admin\model\wanlshop\Qrcode::create([
//                        'image' => 'uploads/qrcode/' . $file,
//                        'status' => 0,
//                        'order_id' => $order_id, // 修正为整数值
//                        'salt' => $salt
//                    ]);
//                } else {
//                    halt(1111111);
                    // 一个商品多个码
                    $goods = Goods::where('id', $orderGoods[0]['goods_id'])->find();
                    // 如果是虚拟商品多码
                    if ($goods['good_type'] == 1) {
                        $spotAllNum = $goods['spot_all_num'];

                        // 如果 $spotAllNum 为空或为 0，将其赋值为 1
                        if (empty($spotAllNum) || $spotAllNum == 0) {
                            $spotAllNum = 1;
                        }
                        for ($i = 0; $i < $spotAllNum; $i++) {
                            $salt = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 16);
                            $file = $fileBaseName . '_' . $i . '.png'; // 添加循环索引到文件名中
                            QRcode::png($salt, $publicPath . 'uploads/qrcode/' . $file);
                            \app\admin\model\wanlshop\Qrcode::create([
                                'image' => 'uploads/qrcode/' . $file,
                                'status' => 0,
                                'order_id' => $order_id, // 修正为整数值
                                'salt' => $salt
                            ]);
                        }
                    } else {
                        $file = $fileBaseName . '.png';
                        QRcode::png($salt, $publicPath . 'uploads/qrcode/' . $file);
                        \app\admin\model\wanlshop\Qrcode::create([
                            'image' => 'uploads/qrcode/' . $file,
                            'status' => 0,
                            'order_id' => $order_id, // 修正为整数值
                            'salt' => $salt
                        ]);
                    }
//                }
            }
        }
    }

    //扫码核销
    public function ScanCode()
    {

        $params = $this->request->param();
        $salt = $params['salt'];
        TestContent::create([
            'content'=>$salt
        ]);
        $qrcode = \app\api\model\wanlshop\Qrcode::where('salt',$salt)->find();
        if($qrcode){
            $order = \app\api\model\wanlshop\Order::where('id',$qrcode['order_id'])->find();
            $qrcodeId = $qrcode['id'];
            $user_id = $this->auth->id;
            $phone =  $this->auth->mobile;
            $verification = Verification::where('address_spot_id',$order['spot_id'])->where('user_id', $user_id)->find();
            $user = \app\common\model\User::where('id', $user_id)->where('spot_id',$order['spot_id'])->find();
            $spotids = AddressSpot::where('phone',$phone)->whereNull('deletetime')->column('id');
            if ($verification || $user || in_array($order['spot_id'], $spotids)) {
                // 用户在核销员列表中
                $OrderGoods = OrderGoods::where('order_id',$order['id'])->select();
                $goods  = Goods::where('id',$OrderGoods[0]['goods_id'])->find();
                //虚拟商品
                if($goods['good_type'] == 1){
                    $spotDayNum = $goods['spot_day_num'];
                    if ($spotDayNum != -1) {
                        //获取今天的核销记录
                        $currentDate = date('Y-m-d');
                        $startOfDayTimestamp = strtotime($currentDate . ' 00:00:00');
                        $endOfDayTimestamp = strtotime($currentDate . ' 23:59:59');
                        $log = QrcodeLog::alias('ql')
                                ->join('wanlshop_qrcode q', 'ql.qrcode_id = q.id','LEFT')
                            ->where('q.order_id', $order['id'])
                            ->whereBetween('ql.updatetime', [$startOfDayTimestamp, $endOfDayTimestamp])
                            ->count();
                        if($log>=$spotDayNum){
                            $this->error(__('今日核销已达上限'));
                        }
                    }
                }
                if($qrcode['status'] == 0){
                    $qrcode->status = 1;
                    $qrcode->updatetime = time();
                    $qrcode->save();
                    //如果此订单的所有核销码都以核销或者过期,订单完成
                    $remainingQrcodes = \app\api\model\wanlshop\Qrcode::where('order_id', $qrcode['order_id'])
                        ->where('status', 0)
                        ->count();
                    if ($remainingQrcodes == 0) {
                        // 如果所有核销码都已核销或过期，将订单状态设置为已完成
                        $order->state = 6; // 根据你的订单状态字段使用实际的值
                        $order->save();
                    }
                    //创建核销记录
                    QrcodeLog::create([
                        'user_id'=>$this->auth->id,
                        'qrcode_id'=>$qrcodeId
                    ]);
                    //虚拟商品
                    if($goods['good_type'] == 1){
                        \app\api\model\wanlshop\Order::where('id',$qrcode['order_id'])->update([
                            'is_refund'=>1
                        ]);
                    }
                    $this->success('核销成功');
                }else{
                    $this->error(__('此核销码不在核销范围内'));
                }

            }else{
                $this->error(__('您不可以核销此码'));
            }
        }else{
            $this->error(__('请扫正确的核销码'));
        }
    }
    //自动确认收货
    public function confirmReceipt()
    {
        $config = get_addon_config('wanlshop');
        $receivingtime = time() - ($config['order']['receiving'] * 86400);  // 自动收货时间
        $orders = \app\api\model\wanlshop\Order::whereIn('state',['3','8','9'])->select();
        foreach ($orders as $order){
            if($order['spot_id']){
                $spot = AddressSpot::where('id',$order['spot_id'])->find();
                //自提店
                if($spot['type'] == 1){
                    //备货时间超过7天就
                    $paymentTime = $order['paymenttime'] + ($spot['cometime']*3600);
                    if($paymentTime < $receivingtime){
                        $order->state = 6;
                        $order->save();
                    }
                }
                //核销店
                if($spot['type'] == 2){
                    //获取需要核销的所有商品
                    $goodsIds = OrderGoods::where('order_id',$order['id'])->column('goods_id');
                    // 获取商品中 spot_end_time 最大的记录
                    $goods = Goods::whereIn('id', $goodsIds)
                        ->order('spot_end_time', 'desc')
                        ->limit(1)
                        ->find();
                    $spotEndTime = strtotime($goods['spot_end_time']);
                    if($spotEndTime < $receivingtime){
                        $order->state = 6;
                        $order->save();
                    }
                }
            }else{
                if($order['paymenttime'] < $receivingtime){
                    $order->state = 6;
                    $order->save();
                }
            }
        }
    }
    //自动分账
    public function separateAccounts(){
        $config = get_addon_config('wanlshop');
        $separatetime = time() - ($config['order']['receiving'] * 86400);  //自动分账时间
        $orders = \app\api\model\wanlshop\Order::whereIn('state',[4,6])
            ->where('taketime','<',$separatetime)
            ->where('is_commission','0')
            ->where('is_integral',0)
            ->select();
//        $orders = \app\api\model\wanlshop\Order::where('id',148)->select();
        foreach ($orders as $order){
            $platform_rake = 0;//平台抽成金额
            $pick_up_rake = 0;//自提点抽成金额
            //实际支付金额
            $pay = \app\admin\model\wanlshop\Pay::where('order_id',$order['id'])
                ->where('pay_type',1)
                ->find();
            if($pay){//判断是否存在微信支付
                $realPrice = $pay['order_price'];  //真实金额
                $price = $pay['price'];  //实际金额
                $score_price = $pay['score_price']; //积分抵扣金额

                //分佣与抽成比例
                //商品>商家>商品分类
                $orderGoods = OrderGoods::where('order_id',$order['id'])->select();

                $pick_up = AddressSpot::where('type',1)->find($order['spot_id']);
                //查看当前商品比例
                foreach ($orderGoods as $orderGood){
                    if(!empty($orderGood['take_proportion'])){
                        $platform_rake = bcadd($platform_rake,$orderGood['take_proportion']/100*$orderGood['price'],2);
                    }
                    if(!empty($orderGood['sharing_proportion']) && $pick_up){
                        $pick_up_rake = bcadd($pick_up_rake,$orderGood['sharing_proportion']/100*$orderGood['price'],2);
                    }
                }


                if($score_price > 0){//扣除订单总抵扣金额
                    $platform_rake = bcsub($platform_rake,$score_price,2);
                }
                $shop = \app\api\model\wanlshop\Shop::find($order['shop_id']);
                $separate = new Separate(null,['sub_mch_id'=>$shop['sub_mchid']]);
                $separate_array = json_decode($pay['notice'],true);
                if($platform_rake > 0 && $pick_up_rake > 0){
                    if($pick_up['spot_type'] == 0){
                        $multiShare = [
                            "type"          => "MERCHANT_ID",
                            "account"       => "{$pick_up['sub_mchid']}",
                            "name"          => "{$pick_up['merchant_name']}",//商户全称
                            "relation_type" => "PARTNER"
                        ];
                    }else{
                        $third = Third::where('user_id',$pick_up['user_id'])->find();
                        $multiShare = [
                            "type"          => "PERSONAL_OPENID",
                            "account"       => "{$third['openid']}",
                            "name"          => "{$pick_up['contacts']}",//商户全称
                            "relation_type" => "PARTNER"
                        ];
                    }
                    $result = $separate->share($separate_array['transaction_id'],$separate_array['out_trade_no'],bcmul($platform_rake,100),'1680098009','悦采科技',$multiShare,bcmul($pick_up_rake,100));
//                    $result = $separate->multiShare($pay['trade_no'],$pay['pay_no'],$receiver,$multiShare);
                }elseif ($platform_rake > 0){
                    $result = $separate->share($separate_array['transaction_id'],$separate_array['out_trade_no'],bcmul($platform_rake,100));
                }else if($pick_up_rake > 0){
                    $pick_up = AddressSpot::find($order['spot_id']);
                    if($pick_up['spot_type'] == 0){
                        $account = $pick_up['sub_mchid'];
                        $name = $pick_up['merchant_name'];
                    }else{
                        $third = Third::where('user_id',$pick_up['user_id'])->find();
                        $account = $third['openid'];
                        $name = $pick_up['contacts'];
                    }
                    $result = $separate->share($separate_array['transaction_id'],$separate_array['out_trade_no'],bcmul($pick_up_rake,100),$account,$name,[],null,$pick_up['spot_type']);
                }
                if($result['bool'] == true){
                    \app\api\model\wanlshop\Order::update(['is_commission'=>1],['id'=>$order['id']]);
                }
            }



        }
    }
    //我的店铺列表
    public function mySpot()
    {
        $spot_id = \app\admin\model\User::where('id',$this->auth->id)->column('spot_id');
        $address_spot_ids = Verification::where('user_id',$this->auth->id)->column('address_spot_id');
        $all_spot_ids = [];
        foreach ($address_spot_ids as $spot_ids) {
            // 使用 explode 将逗号分隔的字符串拆分为数组
            $ids_array = explode(',', $spot_ids);
            // 将拆分后的数组与已有的 spot_ids 合并
            $all_spot_ids = array_merge($all_spot_ids, $ids_array);
        }
        // 将单一的 spot_id 合并到总的数组中
        $all_spot_ids = array_merge($spot_id, $all_spot_ids);

        // 去重
        $unique_spot_ids = array_unique($all_spot_ids);
        // 查询 addressSpot 表
        $address_spots = AddressSpot::whereIn('id', $unique_spot_ids)->select();
        $this->success('成功',$address_spots);
    }
    //是否可查看自提店收益
    public function separateList()
    {
        $spot = AddressSpot::where('type',1)->where('user_id',$this->auth->id)->select();
        $this->success('成功',$spot);
    }
    //是否能结算购物车
    public function isSettlement()
    {
        $goodsList = $this->request->param('goods');
        $goodsList = explode(',', $goodsList);
        $addressSpots = [];
        $delivery_method = 0;
        //是否都是怡亚通
        $is_yyt = null;
        foreach ($goodsList as $good){
            $goods = Goods::where('id',$good)->find();
            if($delivery_method != 0){
                if($delivery_method !=$goods['delivery_method']){
                    $this->error('配送方式不同不能一起下单');
                }
            }
            $shop = \app\api\model\wanlshop\Shop::where('id',$goods['shop_id'])->find();
            // 检查商家类型是否一致
            if ($is_yyt === null) {
                // 第一个商品，记录它的商家类型
                $is_yyt = $shop['shop_type'];
            } else {
                // 比较后续商品的商家类型
                if ($shop['shop_type'] != $is_yyt) {
                    $this->error('商家类型不同，不能一起下单');
                }
            }
            if($goods['good_type']==1){
                if(count($goodsList) > 1){
                    $this->error('虚拟商品只能自成一单');
                }

            }
            if(count($goodsList) > 0) {
                if ($goods['delivery_method'] == 2) {
                    $delivery_method = 2;

                    // 合并自提点 ID
                    $selfAddressSpots = explode(',', $goods['self_address_spot_id']);
                    $platformAddressSpots = explode(',', $goods['platform_address_spot_id']);
                    $addressSpots = array_merge($addressSpots, $selfAddressSpots, $platformAddressSpots);
                }else if ($goods['delivery_method'] == 3) {
                    $delivery_method = 3;
                    // 合并核销点 ID
                    $selfAddressSpots = explode(',', $goods['self_address_spot_id']);
                    $addressSpots = array_merge($addressSpots, $selfAddressSpots);
                }else if($goods['delivery_method'] == 1){
                    $delivery_method = 1;
                }
            }
        }
        if(count($goodsList) > 1 && $delivery_method != 1) {

            // 统计每个自提点出现的次数
            $spotCounts = array_count_values($addressSpots);
            // 提取重复的自提点 ID（出现次数超过1次）
            $duplicateSpots = array_keys(array_filter($spotCounts, function($count) {
                return $count > 1;
            }));
            // 检查是否有统一的自提点
            if (count($duplicateSpots) > 0) {
                // 如果只有一个统一的自提点，可以下单
                $this->success('成功',$delivery_method);
            } else {
                // 如果没有统一的自提点，或者多个重复自提点，抛出错误
                $this->error('商品必须有相同的自提店或核销点才能下单');
            }
        }else{
            $this->success('成功',$delivery_method);
        }
    }
    //自动取消退款
    public function cancelRefund()
    {  $config = get_addon_config('wanlshop');
        $refundTime = time() - ($config['order']['customer'] * 86400);  //取消售后时间
        $orders = \app\api\model\wanlshop\Order::whereIn('state',[4,6])->where('updatetime','<',$refundTime)->where('is_refund',0)->select();
        foreach ($orders as $order){
            \app\api\model\wanlshop\Order::where('id',$order['id'])->update([
               'is_refund'=>1
            ]);
        }
    }
    //团长我的自提店列表
    public function pickupShop()
    {
        $user_id = $this->auth->id;
        $user = \app\admin\model\User::where('id',$user_id)->find();
        $spotIds = AddressSpot::where('phone', $user['mobile'])
            ->whereIn('status', [1, 4])
            ->where('type', 1)
            ->column('id');
        $shopIds = \app\api\model\wanlshop\Order::whereIn('spot_id', $spotIds)
            ->column('shop_id');
        $shopIds = array_unique($shopIds);
        $shops = \app\api\model\wanlshop\Shop::whereIn('id',$shopIds)->select();
        $this->success('成功',$shops);
    }
    //团长自提点收益
    public function pickupStore()
    {
        $shopId  = $this->request->get('shopId');
        $start_time  = $this->request->get('start_time');
        $end_time  = $this->request->get('end_time');
        $type  = $this->request->get('type');
        if($shopId){
            $shops = \app\api\model\wanlshop\Shop::where('id',$shopId)->column('id');
        }else{
            $user_id = $this->auth->id;
            $user = \app\admin\model\User::where('id',$user_id)->find();
            $spotIds = AddressSpot::where('phone', $user['mobile'])
                ->whereIn('status', [1, 4])
                ->where('type', 1)
                ->column('id');
            $shopIds = \app\api\model\wanlshop\Order::whereIn('spot_id', $spotIds)
                ->column('shop_id');
            $shopIds = array_unique($shopIds);
            $shops = \app\api\model\wanlshop\Shop::whereIn('id',$shopIds)->column('id');
        }
        $receiptAmount = 0.00;
        $unreportedAmount = 0.00;
        $orders = \app\admin\model\wanlshop\Order::alias('order')
            ->join('wanlshop_qrcode q', 'order.id = q.order_id', 'LEFT')
            ->with(['shop','spot','pay','ordergoods'])
            ->whereIn('order.shop_id',$shops)
            ->whereIn('order.state',[2,3,4,6,8,9]);

            if ($start_time) {
                $start_timestamp = strtotime($start_time . ' 00:00:00');
                $orders->where('order.paymenttime', '>=', $start_timestamp);
            }
            if ($end_time) {
                $end_timestamp = strtotime($end_time . ' 23:59:59');
                $orders->where('order.paymenttime', '<=', $end_timestamp);
            }
            if ($type == 0) {
                $orders->whereIn('q.status', [0, 3]);
            } elseif ($type == 1) {
                $orders->whereIn('q.status', [1, 2]);
            }
        $orders = $orders->select();
        foreach ($orders as $order){
            $pick_up_rake = 0.00;//自提点抽成金额
            $pick_up = AddressSpot::where('type',1)->find($order['spot_id']);
            foreach ($order['ordergoods'] as $ordergood){
                if(!empty($ordergood['sharing_proportion']) && $pick_up){
                    $pick_up_rake = bcadd($pick_up_rake,$ordergood['sharing_proportion']/100*$ordergood['price'],2);
                }
            }
//            halt($pick_up_rake);
            if($pick_up_rake <= 0){
                $order['pick_up_rake'] = '0.00';
            }else{
                $order['pick_up_rake'] = $pick_up_rake;
            }
            //是否入账
            if($order['is_commission'] == 1){
                //已分账
                $receiptAmount = bcadd($receiptAmount, $pick_up_rake, 2);
            }else{
                //未分账
                $unreportedAmount = bcadd($unreportedAmount, $pick_up_rake, 2);
            }


        }
        $data = [
            'list'=>  $orders,
            'receiptAmount'=>$receiptAmount,
            'unreportedAmount'=>$unreportedAmount,
        ];
        $this->success('成功',$data);
    }
    public function instructions()
    {
        $chatConfig = get_addon_config('wanlshop');
        $instructions = $chatConfig['config']['instructions'];
        $this->success('成功',$instructions);
    }
}